package com.example.nio.controller;

import com.example.nio.commons.*;
import com.example.nio.config.FlowNumHandler;
import com.example.nio.dao.AgentMapper;
import com.example.nio.dto.ChatHistory;
import com.example.nio.dto.StatisReportDto;
import com.example.nio.service.MessageDisposeService;
import com.example.nio.service.StatisReportService;
import com.example.nio.utils.AgentUserUtil;
import com.example.nio.utils.AssignedUtil;
import com.example.nio.utils.StatisReportUtil;
import com.example.nio.vo.AgentServicefall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/agent")
public class AgentController {
    @RequestMapping("/onlineAgent")
    public Result onlineAgent(){
        return Result.ok(AssignedUtil.getAgentByDepartment("1"));
    }
    @Autowired
    private MessageDisposeService messageDisposeService;
    @Autowired
    private FlowNumHandler flowNumHandler;
    @Autowired
    private StatisReportService statisReportService;


    /**
     *
     * @param userId
     * @param agentId
     * @param messageSource
     * @return
     */
    @RequestMapping("/transTourist")
    public Result transTourist(@RequestParam("userId") String userId,@RequestParam("agentId") String agentId,@RequestParam("messageSource") Integer messageSource){
        if (AgentUserUtil.checkUser(userId)){
            // 把上一份聊天记录存起来
            StatisReport statisReportOld = StatisReportUtil.cut(userId);
            statisReportService.add(statisReportOld);
            StatisReportUtil.addStatisReport(userId,"1",agentId,1,messageSource);

            AgentUserUtil.deleteUser(userId);
            Agent agent = AssignedUtil.getAgentByAgentId(agentId);
            AgentUserUtil.addUser(userId,agent);
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setFromUser(userId);
            chatMessage.setToUser(agentId);
            chatMessage.setMsgType("transfer");
            chatMessage.setMessageSource(messageSource);
            messageDisposeService.messageHandling(chatMessage);
            return Result.ok("success");
        }else{
            return Result.error(404,userId + "未连入");
        }
    }

    /**
     * 获取客服历史聊天记录
     * @param chatHistory
     * @return
     */
    @PostMapping("/getChatHistory")
    public Result getChatHistory(@RequestBody ChatHistory chatHistory){
        Page<MMessage> page = flowNumHandler.getChatList(chatHistory.getCurrentPage(), chatHistory.getPageSize(), chatHistory.getUserId(), chatHistory.getContent(),chatHistory.getTimeStart(),chatHistory.getTimeEnd());
        return Result.ok(page);
    }
    @Autowired
    private AgentMapper agentMapper;

    @GetMapping("/addTouristAlias")
    public Result addTouristAlias(@RequestParam("userId") String userId,@RequestParam("aliasName") String aliasName){
        String alias = agentMapper.getAliasByUserId(userId);
        if (alias != null && !"".equals(alias)){
            agentMapper.updateAliasName(userId, aliasName);
        }else {
            agentMapper.addAliasName(userId, aliasName);
        }
        return Result.ok("请求成功");
    }

    @GetMapping("/changestate/{agent}/{state}")
    public Result updateAgentStatus(@PathVariable("agent") String agentId, @PathVariable("state") Integer state){
        try {
            state = state == 0 ? 1 : 0;
            Agent agent = AssignedUtil.getAgentByAgentId(agentId);
            agent.setState(state);
            return Result.ok(state == 1 ?"修改客服状态成功,当前状态：在线":"修改客服状态成功,当前状态：离线");
        }catch (Exception e){
            return Result.error(500,"修改客服状态失败");
        }
    }

    @PostMapping("/logoutAgent")
    public Result logoutAgent(@RequestParam String agentId){
        Agent agent = AssignedUtil.getAgentByAgentId(agentId);
        AgentUserUtil.deleteAgent(agent);
        AssignedUtil.deleteAgent(agent);
        System.out.println("退出指定用户：" + agentId);
        return Result.ok(agentId + "退出成功");
    }
    @PostMapping("/agentServicefall")
    public Result getServicefall(@RequestBody AgentServicefall agentServicefall){
        AgentServicefall servicefall = statisReportService.getAgentServicefall(agentServicefall);
        return Result.ok(servicefall);
    }

    @PostMapping("/getReceptionHistory")
    public Result getReceptionHistory(@RequestBody StatisReportDto statisReportDto){
        if (statisReportDto.getSource() != null){
            if (statisReportDto.getSource() == 1){
                statisReportDto.setChannel("web");
            }else{
                statisReportDto.setChannel("wechat");
            }
        }
        return Result.ok(statisReportService.findAll(statisReportDto));
    }
}

